/*
 * @Description: http 封装
 * @Author: LiuYan
 * @Date: 2021-12-05 13:54:34
 * @LastEditTime: 2023-09-07 23:41:50
 * @LastEditors: 刘岩 15136056318@163.com
 * @Reference:
 */
import axios from 'axios'
import router from '@/router'
import { userStore } from '../store/module.ts'
import config from '../config/index.ts'
import { IFetchParams } from './check.ts'
const { APP } = config
//请求拦截
axios.interceptors.request.use(function (config) {
  if (process.env.NODE_ENV === 'production') config.baseURL = env.VITE_APP_BASE_URL
  return config
})
//响应拦截
axios.interceptors.response.use(res => {
  const _res = res.data
  if (_res.code === 401 && APP.isLogin) {
    router.replace('/login')
  }
  if (_res.code === 500) {
    console.error('500')
  }
  return _res
})
const fetch = (
  params: IFetchParams = {
    url: '',
    method: 'post',
    headers: {
      'content-type': 'application/json',
    },
    token: true,
  }
) => {
  if (params.token && params.headers) {
    const user = userStore()
    params.headers['Authorization'] = user.token
  }
  return new Promise((resolve, reject) => {
    axios({ ...params })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        const res = err.response
        if (res.status === 500) {
          console.error('500')
        }
        reject(err)
      })
  })
}
export default fetch
